﻿using System;
using System.Collections.Generic;
#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using FRL.DebtChased.Extensions;
using FRL.DebtChased.Repository;
using FRL.DebtChased.Repository.ViewModels;
using FRL.DebtChased.Website;

namespace WebApplication.Finance.Controls
{

	/// <summary>
	/// Declaration of ClientCollectorAssignmentCtrl class
	/// </summary>
	public partial class ClientCollectorAssignmentCtrl : System.Web.UI.UserControl
	{

		/////////////////////////////////////////////////////////////
		// Constants

		private const string ContextModeltag = "ContextModel";
		private const string ClientIdTag = "ClientRecordId";

		/////////////////////////////////////////////////////////////
		// Attributes

		private ClientCollectorAssignmentsModel m_contextModel;
		public ClientCollectorAssignmentsModel ContextModel
		{
			get
			{
				if (m_contextModel == null)
					m_contextModel = ViewState[ContextModeltag] as ClientCollectorAssignmentsModel;
				return m_contextModel;
			}
			private set
			{
				ViewState[ContextModeltag] = value;
			}
		}

		public int? ClientRecordID
		{
			get
			{
				return ViewState[ClientIdTag] as int?;
			}
			set
			{
				ViewState[ClientIdTag] = value;
			}
		}

		private Dictionary<int, string> m_collectorMap = null;

		/////////////////////////////////////////////////////////////
		// Event handlers

		protected override void OnPreRender(EventArgs e)
		{

			// Call base-class function
			base.OnPreRender(e);

			// Get the model
			ClientCollectorAssignmentsModel m = ContextModel;

			// Bind the grid
			gridAssignments.DataSource = m.Elements;
			gridAssignments.DataBind();

			// Show/hide controls
			txtNewMaximum.Visible = chkNewMaximum.Checked;
			pnlNewMaximum.Visible = !chkNewMaximum.Checked;

		}

		protected void Page_Load(object sender, EventArgs e)
		{

			// Declare an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Create a dictionary of collectors
				m_collectorMap = User.GetDictionary(ent, Definitions.AllFinExceptSalesAndSysAdmin, false);

				// If this is a postback...
				if (this.IsPostBack)
				{

					// Get the model
					ClientCollectorAssignmentsModel model = ContextModel;
#if DEBUG
					Debug.Assert(model != null);
#endif // #if DEBUG

					// Update model from grid
#if DEBUG
					Debug.Assert(gridAssignments.Rows.Count == model.Elements.Count);
#endif // #if DEBUG
					for (int iRowIndex = 0; iRowIndex < gridAssignments.Rows.Count; iRowIndex++)
					{

						// Get the row
						GridViewRow row = gridAssignments.Rows[iRowIndex];

						// Get the id, type and text
						int id = int.Parse(gridAssignments.DataKeys[iRowIndex].Value.ToString());

						// Find the matching element
						ClientCollectorAssignmentsModel.Element el = model.FindByAssignmentId(id);
#if DEBUG
						Debug.Assert(el != null);
#endif // #if DEBUG

						// Get the collector
						DropDownList cboCollector = row.FindControl("cboCollector") as DropDownList;
						el.UserId = int.Parse(cboCollector.SelectedValue);

						// Get the minimum
						decimal dcMin = 0;
						TextBox txtMinimum = row.FindControl("txtMinimum") as TextBox;
						decimal.TryParse(txtMinimum.Text, out dcMin);
						el.Min = dcMin;

						// Get the maximum
						decimal dcMax = 0;
						TextBox txtMaximum = row.FindControl("txtMaximum") as TextBox;
						decimal.TryParse(txtMaximum.Text, out dcMax);
						el.Max = dcMax;

						// Get the maximum flag
						CheckBox chkMaximum = row.FindControl("chkMaximum") as CheckBox;
						el.HasMaximum = chkMaximum.Checked;

					}

				}
				else
				{
#if DEBUG
					Debug.Assert(ContextModel == null);
#endif // #if DEBUG

					// Load the workflow list model
					ClientCollectorAssignmentsModel m = new ClientCollectorAssignmentsModel(ent, ClientRecordID);
					ContextModel = m;

					// Bind the new collector combo
					cboNewCollector.BindToDictionary(m_collectorMap);
					cboNewCollector.SelectedIndex = 0;

				}

			}

		}

		protected void gridAssignments_RowDataBound(object sender, GridViewRowEventArgs e)
		{

			// If this is a data-row...
			if (e.Row.RowType == DataControlRowType.DataRow)
			{

				// Get the model element
				ClientCollectorAssignmentsModel.Element el = e.Row.DataItem as ClientCollectorAssignmentsModel.Element;

				// Collector combo
				DropDownList cboCollector = e.Row.FindControl("cboCollector") as DropDownList;
				cboCollector.BindToDictionary(m_collectorMap);
				cboCollector.SelectedValue = el.UserId.ToString();

				// Minimum
				TextBox txtMinimum = e.Row.FindControl("txtMinimum") as TextBox;
				txtMinimum.Text = el.Min.ToString("#,0.00");

				// Maximum
				TextBox txtMaximum = e.Row.FindControl("txtMaximum") as TextBox;
				txtMaximum.Text = el.Max.ToString("#,0.00");
				txtMaximum.Visible = el.HasMaximum;

				// Maximum checkbox and panel
				CheckBox chkMaximum = e.Row.FindControl("chkMaximum") as CheckBox;
				Panel pnlMaximum = e.Row.FindControl("pnlMaximum") as Panel;
				chkMaximum.Checked = el.HasMaximum;
				pnlMaximum.Visible = !el.HasMaximum;

			}

		}

		protected void gridAssignments_RowCommand(object sender, GridViewCommandEventArgs e)
		{

			// Get row index
			int iRow = int.Parse(e.CommandArgument.ToString());

			// Convert argument to id
			int iAssignmentId = int.Parse(gridAssignments.DataKeys[iRow].Value.ToString());

			// If this is the delete button...
			if (e.CommandName == "DeleteAssignment")
			{

				// Get the model
				ClientCollectorAssignmentsModel model = ContextModel;
#if DEBUG
				Debug.Assert(model != null);
#endif // #if DEBUG

				// Delete from the model
				ClientCollectorAssignmentsModel.Element el = model.FindByAssignmentId(iAssignmentId);
				if (el != null)
				{

					// Remove, rebind and reload user control
					model.Elements.Remove(el);

				}
#if DEBUG
				else
					Debug.Assert(false);
#endif // #if DEBUG

			}

		}

		protected void butAdd_Click(object sender, EventArgs e)
		{

			// Get the model
			ClientCollectorAssignmentsModel model = ContextModel;
#if DEBUG
			Debug.Assert(model != null);
#endif // #if DEBUG

			// Get the new collector
			int iCollectorId = int.Parse(cboNewCollector.SelectedValue.ToString());

			// If the user is already in the model...
			if (model.ContainsCollectorId(iCollectorId) != null)
			{

				// Update the error
				(this.Page.Master as FinanceMaster).ErrorMessage = "This collector already has an assignment.";

			}
			else
			{

				// Get the next new assignment id
				int iNewAssignmentId = model.GetNextNewId();

				// Get the minimum amount
				decimal dcMinimum = 0;
				decimal.TryParse(txtNewMinimum.Text, out dcMinimum);
				dcMinimum = Math.Max(0, dcMinimum);

				// Get the maximum amount
				decimal dcMaximum = 0;
				decimal.TryParse(txtNewMaximum.Text, out dcMaximum);
				dcMaximum = Math.Max(0, dcMaximum);

				// Create a new model element
				ClientCollectorAssignmentsModel.Element el = new ClientCollectorAssignmentsModel.Element(iNewAssignmentId);
				el.UserId = iCollectorId;
				el.Min = dcMinimum;
				el.Max = dcMaximum;
				el.HasMaximum = chkNewMaximum.Checked;
				model.Elements.Add(el);

			}

		}

		protected void onSetupControlsEvent(object sender, EventArgs e)
		{

		}

	}

}